from django.db import models
from .exceptions import *

# Create your models here.
class User(models.Model):
    account = models.EmailField(unique=True)
    password = models.CharField(max_length=100)

    @classmethod
    def register(cls,account,password,*args,**kwargs):
        #先判断是否存在
        if cls.objects.filter(account=account).count()==1:
            raise UserExistException('用户已存在')
        else:
            #创建新用户
            user = cls.objects.create(account=account,password=password)
            return user

    @classmethod
    def is_exist(cls, account):
        if cls.objects.filter(account=account).count()==1:
            return True
        else:
            return False

    @classmethod
    def login(cls,account,password,time,*args,**kwargs):
        if cls.objects.filter(account=account,password=password).count()==0:
            raise UserNotExistException('用户不存在')
        else:
            #判断客户端时间和服务器时间不能相差超过10分钟
            import time as t
            current = t.time()*1000
            ctime = int(time)
            start = current - 1000*60*10
            if not(ctime > start and ctime < current):
                raise  Exception('时间不对')

            return cls.objects.get(account=account,password=password)

#收货地址模型
class Address(models.Model):
    uname = models.CharField(max_length=20,verbose_name='收货人')
    phone = models.CharField(max_length=11,verbose_name='手机号')
    address = models.CharField(max_length=100,verbose_name='收货地址')
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    isdefault = models.BooleanField(default=False,verbose_name='是否默认地址')